package yxy.apple.protobuf.utility.generator;

import java.io.File;
import java.io.IOException;

import com.alibaba.fastjson.JSONObject;

public class JavaConstantsGenerator extends ConstantsGenerator {

	private String className = "Noname";
	private String packageName = null;

	public JavaConstantsGenerator(boolean trusted, String packageName, String className) {
		super(trusted);
		this.packageName = packageName;
		this.className = className;
	}

	@Override
	@Deprecated
	public void generate(JSONObject json, File output, String encoding) throws IOException {
		super.generate(json, output, encoding);
	}

	public void generate(JSONObject json, String src, String encoding) throws IOException {
		String filename = this.className + ".java";
		String path = src + "/" + this.packageName.replaceAll("\\.", "/");
		File output = new File(path + "/" + filename);
		this.generate(json, output, encoding);
	}

	@Override
	protected String assembleField(int level, String parent, String type, String name, String comment, String value) {
		String indentation = this.indent(level);
		StringBuffer buffer = new StringBuffer();
		if (comment != null) {
			buffer.append(String.format("%s//%s\r\n", indentation, comment));
		}
		if (parent != null && parent.equals("enum")) {
			buffer.append(String.format("%s%s = %s,\r\n", indentation, name, value));
		} else {
			String format = "%spublic static final %s %s = %s;\r\n";

			if (type.endsWith("String")) {
				format = "%spublic static final %s %s = \"%s\";\r\n";
			}
			buffer.append(String.format(format, indentation, type, name, value));
		}
		return buffer.toString();
	}

	@Override
	protected String assembleHeader(int level, String type, String name, String comment) {
		String indentation = this.indent(level);
		StringBuffer buffer = new StringBuffer();

		if (comment != null) {
			buffer.append(String.format("\r\n%s//%s\r\n", indentation, comment));
		}
		if (level == 0 && type == null) {
			buffer.append(String.format("package %s;\r\n", packageName));
			buffer.append("// ******************************\r\n");
			buffer.append("// 本文件由ProtobufCompiler自动生成\r\n");
			buffer.append("// *******************************\r\n");
			buffer.append(String.format("public class %s {\r\n", className));
		} else if (type != null && type.equals("class")) {
			buffer.append(String.format("%spublic static final class %s {\r\n", indentation, name));
		} else if (type != null && type.equals("enum")) {
			buffer.append(String.format("%spublic static enum %s {\r\n", indentation, name));
		} else {
			buffer.append(String.format("%s{\r\n", indentation));
		}
		return buffer.toString();
	}

	@Override
	protected String assembleFooter(int level, String type, String name, String comment) {
		String indentation = this.indent(level);
		return String.format("%s}\r\n", indentation);
	}
}
